package com.jx.driving.protocol.terminal.codec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;

/**
 * 对象读写器
 * 
 * @author shenliuyang
 *
 *         2016年8月14日下午2:57:11
 */
public class ObjectReaderWriter extends FieldReaderWriter {

	private ClassReaderWriter rw;

	public ObjectReaderWriter(Field field, int size, int order) {
		super(field, size, order);
		try {
			rw = new ClassReaderWriter(field.getType());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void read(InputStream in, Object to) throws IOException {
		if (in.available() == 0) {
			return;
		}
		try {
			wrtietoField(to, rw.read(in));
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	@Override
	public void write(OutputStream out, Object from) throws IOException {
		Object data = readFromField(from);
		if (data == null) {
			return;
		}
		try {
			rw.write(out, data);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

}
